<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="客户姓名" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="客户电话" prop="customerPhone">
        <el-input v-model="queryParams.customerPhone" placeholder="请输入客户电话" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="订单标题" prop="orderTitle">
        <el-input v-model="queryParams.orderTitle" placeholder="请输入订单标题" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleCreateLink"
          v-hasPermi="['dashboard:submissions:add']"
        >客户需求信息链接</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dashboard:submissions:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="submissionsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="客户电话" align="center" prop="customerPhone" />
      <el-table-column label="订单标题" align="center" prop="orderTitle" :show-overflow-tooltip="true" />
      <el-table-column label="项目类型" align="center" prop="projectType" :show-overflow-tooltip="true" />
      <el-table-column label="程序类型" align="center" prop="techType" :show-overflow-tooltip="true"/>
      <el-table-column label="交付物" align="center" prop="deliverable" :show-overflow-tooltip="true"/>
      <el-table-column label="学校" align="center" prop="school" :show-overflow-tooltip="true" />
      <el-table-column label="专业" align="center" prop="specialty" :show-overflow-tooltip="true" />
      <el-table-column label="硬件环境" align="center" prop="hardware" :show-overflow-tooltip="true" />
      <el-table-column label="需求简介" align="center" prop="introduce" :show-overflow-tooltip="true" />
      <el-table-column label="期望金额" align="center" prop="rewardAmount" />
      <el-table-column label="期望截止" align="center" prop="estimatedEndTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimatedEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusTag(scope.row.status)">{{ formatStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="reviewerName" />
      <el-table-column label="审核备注" align="center" prop="reviewNotes" :show-overflow-tooltip="true" />
      <el-table-column label="提交时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 'PENDING_REVIEW'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleReview(scope.row)"
            v-hasPermi="['dashboard:submissions:edit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dashboard:submissions:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body custom-class="review-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12"><el-form-item label="客户姓名" prop="customerName">{{ form.customerName }}</el-form-item></el-col>
          <el-col :span="12"><el-form-item label="客户电话" prop="customerPhone">{{ form.customerPhone }}</el-form-item></el-col>
        </el-row>
         <el-row>
          <el-col :span="12"><el-form-item label="学校" prop="school">{{ form.school }}</el-form-item></el-col>
          <el-col :span="12"><el-form-item label="专业" prop="specialty">{{ form.specialty }}</el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><el-form-item label="订单标题" prop="orderTitle">{{ form.orderTitle }}</el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="项目类型" prop="projectType">{{ form.projectType }}</el-form-item></el-col>
          <el-col :span="12"><el-form-item label="程序类型" prop="techType">{{ form.techType }}</el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><el-form-item label="交付物" prop="deliverable">{{ form.deliverable }}</el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="期望金额" prop="rewardAmount">¥{{ form.rewardAmount }}</el-form-item></el-col>
          <el-col :span="12"><el-form-item label="期望截止" prop="estimatedEndTime">{{ form.estimatedEndTime }}</el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><el-form-item label="硬件环境" prop="hardware">{{ form.hardware }}</el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><el-form-item label="需求简介" prop="introduce">{{ form.introduce }}</el-form-item></el-col>
        </el-row>
        <el-row v-if="!isApproveAction">
          <el-col :span="24">
            <el-form-item label="拒绝理由" prop="reviewNotes">
              <el-input v-model="form.reviewNotes" type="textarea" placeholder="请输入拒绝理由" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleApprove">审核通过</el-button>
        <el-button type="danger" @click="handleReject">审核拒绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.review-dialog .el-form-item {
  border-bottom: 1px solid #EBEEF5;
  margin-bottom: 0;
  padding: 10px;
}
.review-dialog .el-form-item__label {
  font-weight: bold;
  color: #606266;
}
.review-dialog .el-row {
  border-top: 1px solid #EBEEF5;
  border-left: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}
.review-dialog .el-col {
  border-right: 1px solid #EBEEF5;
}
.review-dialog .el-col:last-child {
  border-right: none;
}
.review-dialog .el-dialog__body {
  padding: 10px 20px 30px 20px;
}

/* Add this new style */
.custom-link-alert {
  width: 600px;
  max-width: 90vw;
}

.custom-link-alert .el-input__inner {
  border-color: #DCDFE6;
  background-color: #F5F7FA;
  color: #606266;
}

/* 手动复制对话框样式 */
.copy-fail-dialog {
  width: 500px;
  max-width: 90vw;
}

.copy-fail-dialog .el-message-box__content {
  padding: 20px;
}

.copy-fail-dialog code {
  user-select: all;
  cursor: text;
}

</style>

<script>
import { listSubmissions, getSubmissions, delSubmissions, createLink, approveSubmission, rejectSubmission, exportSubmissions } from "@/api/dashboard/submissions";

export default {
  name: "Submissions",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      submissionsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        customerPhone: null,
        orderTitle: null,
        status: "PENDING_REVIEW", // 默认查询待审核
      },
      form: {},
      rules: {
        reviewNotes: [
          { required: true, message: "拒绝理由不能为空", trigger: "blur" }
        ],
      },
      statusOptions: [
        { value: "PENDING_REVIEW", label: "待审核" },
        { value: "APPROVED", label: "已通过" },
        { value: "REJECTED", label: "已拒绝" },
        { value: "PENDING_CLIENT", label: "待客户填写" },
      ],
      isApproveAction: true,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      //确保params存在
      this.queryParams.params = this.queryParams.params || {};
      listSubmissions(this.queryParams).then(response => {
        this.submissionsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        customerName: null,
        customerPhone: null,
        orderTitle: null,
        school: null,
        specialty: null,
        projectType: null,
        hardware: null,
        introduce: null,
        techType: null,
        deliverable: null,
        estimatedEndTime: null,
        rewardAmount: null,
        reviewNotes: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.status = "PENDING_REVIEW";
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleCreateLink() {
      createLink().then(response => {
        const link = response.data;
        const h = this.$createElement;
        this.$msgbox({
          title: '链接已生成',
          message: h('div', null, [
            h('p', { style: { marginBottom: '10px' } }, '请将此链接发送给客户，或直接复制：'),
            h('el-input', {
              props: {
                value: link,
                readonly: true
              },
              attrs: {
                id: 'generated-link-input' // for e2e testing or specific selection
              }
            }),
            h('div', { style: { textAlign: 'center', marginTop: '15px' } }, [
              h('el-button', {
                props: {
                  type: 'cyan',
                },
                on: {
                  click: () => {
                    // 先尝试直接复制输入框内容
                    const inputElement = document.getElementById('generated-link-input');
                    if (inputElement) {
                      inputElement.select();
                      inputElement.setSelectionRange(0, inputElement.value.length);
                      if (document.execCommand('copy')) {
                      this.$modal.msgSuccess("链接已复制到剪贴板");
                        return;
                      }
                    }
                    // 如果直接复制失败，使用备用方法
                    this.copyToClipboard(link);
                  }
                }
              }, '一键复制')
            ])
          ]),
          showConfirmButton: true,
          confirmButtonText: '关闭',
          showCancelButton: false,
          customClass: 'custom-link-alert',
        }).catch(() => {});
      });
    },
    handleReview(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getSubmissions(id).then(response => {
        this.form = response.data;
        this.title = "审核订单";
        this.open = true;
      });
    },
    handleApprove() {
      const submissionData = this.form;
      const query = {
        submissionId: submissionData.id,
        deliverable: submissionData.deliverable,
      };

      // 关闭当前审核对话框
      this.open = false;

      this.$router.push({
        path: '/dashboard/orders',
        query: query
      });
    },
    handleReject() {
        this.isApproveAction = false;
        this.$refs["form"].validate(valid => {
            if (valid) {
                rejectSubmission(this.form.id, { reviewNotes: this.form.reviewNotes }).then(() => {
                    this.open = false;
                    this.getList();
                    this.$modal.msgSuccess("已拒绝该提交");
                });
            }
        });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的提交记录？').then(function() {
        return delSubmissions(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('dashboard/submissions/export', {
        ...this.queryParams
      }, `submissions_${new Date().getTime()}.xlsx`);
    },
    formatStatus(status) {
        const statusMap = {
            "PENDING_REVIEW": "待审核",
            "APPROVED": "已通过",
            "REJECTED": "已拒绝",
            "PENDING_CLIENT": "待客户填写"
        };
        return statusMap[status] || "未知";
    },
    getStatusTag(status) {
        const tagMap = {
            "PENDING_REVIEW": "warning",
            "APPROVED": "success",
            "REJECTED": "danger",
            "PENDING_CLIENT": "info"
        };
        return tagMap[status] || "info";
    },

    // 复制到剪贴板功能
    copyToClipboard(text) {
      // 方法1: 使用隐藏的 input 元素
      try {
        const input = document.createElement('input');
        input.setAttribute('readonly', 'readonly');
        input.setAttribute('value', text);
        input.style.position = 'absolute';
        input.style.left = '-9999px';
        document.body.appendChild(input);
        
        // 选择文本
        input.select();
        input.setSelectionRange(0, input.value.length);
        
        // 尝试复制
        const successful = document.execCommand('copy');
        document.body.removeChild(input);
        
        if (successful) {
          this.$modal.msgSuccess("链接已复制到剪贴板");
          return;
        }
      } catch (err) {
        console.log('方法1失败:', err);
      }
      
      // 方法2: 使用 textarea 元素
      try {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.top = '0';
        textarea.style.left = '0';
        textarea.style.width = '2em';
        textarea.style.height = '2em';
        textarea.style.padding = '0';
        textarea.style.border = 'none';
        textarea.style.outline = 'none';
        textarea.style.boxShadow = 'none';
        textarea.style.background = 'transparent';
        document.body.appendChild(textarea);
        
        textarea.focus();
        textarea.select();
        
        const successful = document.execCommand('copy');
        document.body.removeChild(textarea);
        
        if (successful) {
          this.$modal.msgSuccess("链接已复制到剪贴板");
          return;
        }
      } catch (err) {
        console.log('方法2失败:', err);
      }
      
      // 方法3: 使用 Clipboard API (如果支持)
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(() => {
          this.$modal.msgSuccess("链接已复制到剪贴板");
        }).catch((err) => {
          console.log('Clipboard API 失败:', err);
          this.showManualCopyDialog(text);
        });
      } else {
        // 方法4: 显示手动复制对话框
        this.showManualCopyDialog(text);
      }
    },
    
    // 显示手动复制对话框
    showManualCopyDialog(text) {
      this.$alert(`复制失败，请手动复制以下链接：<br><br><code style="background:#f5f5f5;padding:8px;border-radius:4px;display:block;word-break:break-all;font-size:12px;line-height:1.4;">${text}</code>`, '复制失败', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        customClass: 'copy-fail-dialog'
      });
    }
  }
};
</script>
